package com.youdianstar.app.ui.pay

import android.app.Dialog
import android.content.Intent
import android.view.View
import android.widget.CompoundButton
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.entity.CouponRes
import com.youdianstar.app.entity.OrderInfo
import com.youdianstar.app.entity.*
import com.youdianstar.app.adapter.PaymentMethodAdapter
import com.youdianstar.app.databinding.ActivityPaymentCodeBinding
import com.youdianstar.app.support.imp.ICardPayListener
import com.youdianstar.app.util.*
import com.youdianstar.app.common.BisType
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.DataCode
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.ex.*
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.*
import com.youdianstar.app.common.ConfigKey
import com.youdianstar.app.ui.web.WebActivity

import com.stripe.android.ApiResultCallback
import com.stripe.android.PaymentIntentResult
import com.stripe.android.Stripe
import com.stripe.android.model.*
import com.gyf.immersionbar.ImmersionBar
import com.stripe.android.PaymentConfiguration
import com.stripe.android.googlepaylauncher.GooglePayPaymentMethodLauncher
import com.stripe.android.stripecardscan.cardscan.CardScanSheet
import com.stripe.android.stripecardscan.cardscan.CardScanSheetResult
import com.youdianstar.app.common.auko.startActivity
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.Locale


/**
 * File: PaymentCodeActivity
 * Author: 82149 Create: 2021/11/26 14:23
 * Changes (from 2021/11/26)
 * --------------------------------------------------
 * description: 支付页面
 * ---------------------------------------------------
 *
 */
class PaymentCodeActivity : BaseActivity<ActivityPaymentCodeBinding, PaymentViewModel>() {
    override fun layoutId(): Int = R.layout.activity_payment_code

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): PaymentViewModel {
        val model: PaymentViewModel by viewModel()
        return model
    }

    //业务标志
    var payBisType = 0
    //原支付金额（外部传入）
    var amount: Double = 0.0
    //实际支付金额（接口计算后）
    var payAmount: Double = 0.0
    //税率
    var tax:Double = 0.0
    //税金
    var taxAmount = 0.0
    private var countryTx: String = "" //国家代码
    private var symbolTx :String = ""
    private var currencyTx: String = ""
    //业务：支付 订单or报失
    private var orderNo: String = ""
    private var orderInfo: OrderInfo? = null
    private var isShowOrder = false //标记展开订单信息
    //业务：支付 优惠券(弃用)
    private var couponId: String? = null
    //业务：支付 充电卡
    private var chargingId: Int = 0

    private var stripe: Stripe? = null
    private var googleMethodLauncher : GooglePayPaymentMethodLauncher?=null
    private var isGoogleReady = false
    private var stripeScanSheet : CardScanSheet?=null
    private var cardPayParams: PaymentMethodCreateParams? = null
    private var cardPayDialog: SheetPaymentDialog? = null
    private var paymentResult: PaymentResult? = null

    private var payMethodAdapter: PaymentMethodAdapter? = null
    private var bindCardSize = 0 //已绑定卡数量，上限到后不显示添加到支付方式选项
    //选择的支付方式类型, 0：已绑定卡支付，1：输卡号支付 2：亲情圈支付 3：Apple 4:google 5:paypal
    private var payMethod = 0
    private var selectedMethodIndex = 0
    //标志位 订单免单
    private var isPaymentFree = false
    //标志位 标记 正在请求新卡支付
    private var isRequestCard = false
    private var cardNum: String = "" //新卡支付后4位
    //优惠券列表
    private val couponList = mutableListOf<CouponRes>()
    private var selectCouponIndex = -1
    private var couponSelectId: Int = -1
    private var couponSheetDialog: Dialog? = null
    private var isCouponNetTag = false //标识是否请求优惠券接口

    override fun initViewLayout() {
        super.initViewLayout()
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .statusBarColor(R.color.white)
            .titleBarMarginTop(mBinding.lgInnerBg)
            .init()
        //支付按钮选择
        mBinding.boxDefault.isChecked = true
        mBinding.boxDefault.setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(button: CompoundButton?, isCheck: Boolean) {
                updateButtonStateLayout()
            }
        })
        //设置支付方式列表
        mBinding.rcyMethod.layoutManager = LinearLayoutManager(this)
        payMethodAdapter = PaymentMethodAdapter(this, mutableListOf(),object:PaymentMethodAdapter.ItemSelectListener{
            override fun onNewCardAction() {
                if (isPaymentFree)
                    showFreePaymentNotify()
                else{
                    showSheetCardPay()//New Card Payment
                }
            }

            override fun onItemSelectAction(index: Int, isChecked: Boolean) {
                selectedMethodIndex = if (isChecked) index else 0
                updateButtonStateLayout()
            }
        })
        mBinding.rcyMethod.adapter = payMethodAdapter
    }

    override fun initData() {
        super.initData()
        stripe = initStripe(this)
        stripeScanSheet = CardScanSheet.create(from = this,
            stripePublishableKey = PaymentConfiguration.getInstance(this).publishableKey, { cardScanSheetResult ->
                when (cardScanSheetResult){
                    is CardScanSheetResult.Completed->{
                        LogUtil.i("Stripe scan pan:"+cardScanSheetResult.scannedCard.pan)
                        cardPayDialog?.setScanNumber(cardScanSheetResult.scannedCard.pan)
                    }

                    is CardScanSheetResult.Canceled->{
                        LogUtil.d("Stripe scan canceled")
                    }

                    else -> {
                        LogUtil.e("Stripe scan error:$cardScanSheetResult")
                    }
                }
            })
        payBisType = intent.getIntExtra(Extra.IT_TYPE, 0)
        amount = intent.getDoubleExtra(Extra.IT_MONEY, 0.0)
        when (payBisType) {
            BisType.Bis_Rent, BisType.Bis_Loss -> {
                orderNo = intent.getStringExtra(Extra.IT_ORDERNO) ?: ""
                orderInfo = intent.getObject(Extra.IT_DATA)
            }
            BisType.Bis_Coupon -> {
                couponId = intent.getStringExtra(Extra.IT_COUPON) ?: ""
            }
            BisType.Bis_ChargingCard -> {
                chargingId = intent.getIntExtra(Extra.IT_CHARGING,0)
            }
        }
        LogUtil.d("----Intent : type = " + payBisType + ";amount = " + amount + ";order = " + orderInfo?.toString())
        //设置顶部UI包含支付金额,与底部协议+按钮;
        setTopBarLayout()
        //Google 初始化要放到数据设置之后
        googleMethodLauncher = initGoogleMethodLauncher(this, countryCode = countryTx,
            readyCallback = { isReady ->
                LogUtil.d("---Pay google ready: $isReady")
                isGoogleReady = isReady
                payMethodAdapter?.updateMethodEnable(DataCode.Type_Google,isReady)
            }, resultCallback = object : GooglePayPaymentMethodLauncher.ResultCallback{
                override fun onResult(result: GooglePayPaymentMethodLauncher.Result) {
                    onPaymentMethodResult(result, onPaySuccess = { paymentMethodId ->
                        if (!StrUtil.isEmpty(paymentMethodId)){
                            payByGoogle(paymentMethodId)
                        }
                    }, onPayError = { msg ->
                        if (msg == "AT-canceled"){
                            toastShow(getString(R.string.public_cancel), type = 1)
                        }else{
                            toastShow(msg)
                        }
                    })
                }
            })
        if (payBisType == BisType.Bis_Rent || payBisType == BisType.Bis_Loss){
            setOrderSheetLayout()
        }
        if (payBisType == BisType.Bis_Loss || payBisType == BisType.Bis_ChargingCard){
            //后台计算金额
            mViewModel.getPaymentPrice(payBisType, orderNo,null, if (payBisType == BisType.Bis_ChargingCard) chargingId else null)
        }else{
            //直接获取支付方式
            mViewModel.getPaymentMethod(payBisType, amount, orderNo)
        }
    }

    override fun onResume() {
        super.onResume()
        isRequestCard = false
        mViewModel.isPaying = false
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.methodResultLiveData.observe(this, object : BaseApiResultObserver<PaymentMethodResult>() {
                override fun onDataResult(data: PaymentMethodResult?) {
                    super.onDataResult(data)
                    dismissDialog()
                    data?.let {
                        setMethodList(it)
                    }
                }

                override fun onNetError(code: Int, e: String?) {
                    super.onNetError(code, e)
                    dismissDialog()
                    toastShow(e)
                }
            })

        mViewModel.paymentResultLiveData.observe(this, object : BaseApiResultObserver<PaymentResult>() {
                override fun onDataResult(data: PaymentResult?) {
                    super.onDataResult(data)
                    dismissDialog()
                    mViewModel.isPaying = false
                    data?.let {
                        if (it.type == 0)
                            it.type = payBisType
                        when (it.success) {
                            // 1:成功 2：失败 3:需要校验
                            1 -> {
                                paymentResult = null
                                toResultActivity(true, it)
                            }

                            2 -> {
                                paymentResult = null
                                toResultActivity(false, it)
                            }

                            3 -> {
                                paymentResult = it
                                requestAppPayment(it.clientSecret, cardPayParams) {
                                    showLoadingDialog("")
                                }
                            }
                        }
                    }
                }

                override fun onNetError(code: Int, e: String?) {
                    super.onNetError(code, e)
                    dismissDialog()
                    toastShow(e)
                    mViewModel.isPaying = false
                }
            })

        mViewModel.addResultLiveData.observe(this, object : BaseApiResultObserver<Any>() {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                //绑定新卡
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                toastShow(e)
            }
        })

        mViewModel.couponResLiveData.observe(this, object : BaseApiResultObserver<List<CouponRes>>(true) {
                override fun onDataResult(data: List<CouponRes>?) {
                    super.onDataResult(data)
                    couponList.clear()
                    data?.let {
                        couponList.addAll(it)
                        selectCouponIndex = if (it.isNotEmpty()) 0 else -1
                    }
                    isCouponNetTag = true
                    setCouponLayout(if (couponList.isNotEmpty()) couponList[0] else null)
                    //更新优惠券UI+更新底部占位高度
//                    mBinding.couponHolder.visibility = if (couponList.isEmpty()) View.GONE else View.VISIBLE
//                    mBinding.llCouponSelect.visibility = if (couponList.isEmpty()) View.GONE else View.VISIBLE
//                    val innerParams : ConstraintLayout.LayoutParams = mBinding.lgInnerBg.layoutParams as ConstraintLayout.LayoutParams
//                    innerParams.height = ScreenUtil.dp2px(this@PaymentCodeActivity,if (couponList.isEmpty()) 178F else 222F).toInt()
//                    mBinding.lgInnerBg.layoutParams = innerParams
                }

                override fun onNetError(code: Int, e: String?) {
                    super.onNetError(code, e)
                    isCouponNetTag = false
                    setCouponLayout(null)
//                    mBinding.couponHolder.visibility = View.GONE
//                    mBinding.llCouponSelect.visibility = View.GONE
                }
            })

        mViewModel.priceResultLiveData.observe(this, object : BaseApiResultObserver<OrderInfo>() {
            override fun onDataResult(data: OrderInfo?) {
                super.onDataResult(data)
                dismissDialog()
                //计算支付金额与获取订单信息
                data?.let { priceInfo ->
                    payAmount = priceInfo.money
                    tax = priceInfo.tax
                    taxAmount = priceInfo.taxAmount
                    isPaymentFree = priceInfo.isFree
                    mBinding.tvAmount.text = symbolTx+MathUtil.round(payAmount)
                    //更改支付订单信息
                    orderInfo = priceInfo
                }
                //更新支付方式列表(报失 先获取金额再更新支付方式列表)
                payMethodAdapter?.let { adapter ->
                    if (adapter.data.isEmpty())
                        mViewModel.getPaymentMethod(payBisType, payAmount ,orderNo)
                }
                if (payBisType == BisType.Bis_ChargingCard){
                    if (tax>0){
                        mBinding.tvTaxNotify.text = "("+getString(R.string.pay_includingTax)+" "+MathUtil.round(tax) + "%)"
                        mBinding.tvTaxNotify.visibility = View.VISIBLE
                    }else{
                        mBinding.tvTaxNotify.visibility = View.GONE
                    }
                }else{
                    //更新订单信息(订单支付UI)
                    setOrderSheetLayout()
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                if (StrUtil.isEmpty(e)){
                    toastShow(getString(R.string.toast_dataError))
                }else
                    toastShow(e)
                //更新支付方式列表
                payMethodAdapter?.let { adapter ->
                    if (adapter.data.isEmpty())
                        mViewModel.getPaymentMethod(payBisType, amount ,orderNo)
                }
            }
        })
    }

    override fun initClickEvent() {
        mBinding.ivBack.setThrottleListener {
            finish()
        }

        mBinding.ivDetails.setThrottleListener {
            if (payBisType == BisType.Bis_Rent || payBisType == BisType.Bis_Loss){
                if (!isShowOrder)
                    showOrderSheet()
                else{
                    isShowOrder = false
                    mBinding.blurSpring.visibility = View.GONE
                    mBinding.viewOrders.visibility = View.GONE
                }
            }
        }

        mBinding.viewOrders.setThrottleListener {
            isShowOrder = false
            mBinding.blurSpring.visibility = View.GONE
            mBinding.viewOrders.visibility = View.GONE
        }

        mBinding.blurSpring.setThrottleListener {
            isShowOrder = false
            mBinding.blurSpring.visibility = View.GONE
            mBinding.viewOrders.visibility = View.GONE
        }

        mBinding.btnPay.setThrottleListener {
            if (isPaymentFree){
                showFreePaymentNotify()
                return@setThrottleListener
            }
            payMethodAdapter?.getSelectItem()?.run {
                payMethod = this.type
                when (payMethod) {
                    DataCode.Type_Card -> {
                        payByBindCard(this)
                    }

                    DataCode.Type_Google -> {
                        requestGooglePayment(payAmount)
                    }

                    else -> {
                        toastShow(getString(R.string.home_selPaymentMethod))
                    }
                }
            }?:toastShow(getString(R.string.home_selPaymentMethod))
        }

        mBinding.llCouponSelect.setThrottleListener {
            if (isCouponNetTag)
                showCouponSheet()
            else{
                mViewModel.getCouponsList(orderNo, isShow = true)
            }
        }

        //支付协议
        mBinding.tvAgreeContent.setThrottleListener {
            val language = LanguageConfig.instance.getLanguageCode().uppercase(Locale.ROOT)
            val urlTx = DataAppManager.instance.getConfig(ConfigKey.CONFIG_DEPOSIT_URL)+"?lang="+language
            val titleTx = getString(R.string.login_depositAgreement)
            startActivity<WebActivity>(
                Extra.IT_DATA to urlTx,
                Extra.IT_NOTIFY to titleTx
            )
        }
    }

    /**
     * 设置顶部布局
     * --填充支付信息
     */
    private fun setTopBarLayout() {
        when (payBisType) {
            BisType.Bis_Rent -> {
                mBinding.tvDueTo.text = String.format(getString(R.string.home_forTx), getString(R.string.pay_rental))
                mBinding.ivDetails.visibility = View.VISIBLE
                mBinding.lineCoupon.visibility= View.VISIBLE
                mBinding.llCouponSelect.visibility = View.VISIBLE
                mBinding.couponHolder.visibility = View.VISIBLE
                val innerParams : ConstraintLayout.LayoutParams = mBinding.lgInnerBg.layoutParams as ConstraintLayout.LayoutParams
                innerParams.height = ScreenUtil.dp2px(this@PaymentCodeActivity,222F).toInt()
                mBinding.lgInnerBg.layoutParams = innerParams
                mViewModel.getCouponsList(orderNo, isShow = false)
                mBinding.llAgreement.visibility = View.GONE
            }

            BisType.Bis_Deposit -> {
                mBinding.tvDueTo.text = String.format(getString(R.string.home_forTx), getString(R.string.pay_deposit))
                mBinding.ivDetails.visibility = View.GONE //押金不显示提示
                mBinding.lineCoupon.visibility = View.INVISIBLE
                mBinding.llCouponSelect.visibility = View.GONE
                mBinding.couponHolder.visibility = View.GONE
                setAgreementLine(mBinding.tvAgreeContent,part1Tx = getString(R.string.login_agreeTo)+" ",String.format(getString(R.string.login_TxContent),getString(R.string.login_depositAgreement)),"")
                mBinding.llAgreement.visibility = View.VISIBLE
            }

            BisType.Bis_Loss -> {
                mBinding.tvDueTo.text = String.format(getString(R.string.home_forTx), getString(R.string.pay_powerbank)) //报失按买宝处理
                mBinding.ivDetails.visibility = View.VISIBLE
                mBinding.lineCoupon.visibility = View.INVISIBLE
                mBinding.llCouponSelect.visibility = View.GONE
                mBinding.couponHolder.visibility = View.GONE
                mBinding.llAgreement.visibility = View.GONE
            }

            BisType.Bis_ChargingCard -> {
                mBinding.tvDueTo.text = String.format(getString(R.string.home_forTx), getString(R.string.charge_card)) //报失按买宝处理
                mBinding.ivDetails.visibility = View.GONE
                mBinding.lineCoupon.visibility = View.INVISIBLE
                mBinding.llCouponSelect.visibility = View.GONE
                mBinding.couponHolder.visibility = View.GONE
                mBinding.llAgreement.visibility = View.GONE
            }
        }
        payAmount = amount
        countryTx = DataAppManager.instance.countryTx()
        symbolTx = DataAppManager.instance.symbolTx()
        currencyTx = DataAppManager.instance.currencyTx()
        isPaymentFree = false
        mBinding.tvAmount.text = symbolTx+ MathUtil.round(amount)

        updateButtonStateLayout()
    }

    /**
     * 更新按钮状态
     * --押金场景: 勾选协议+选中支付方式,原支付金额>0
     * --其他场景: 选中支付方式,原支付金额>0
     */
    private fun updateButtonStateLayout(){
        if (payBisType == BisType.Bis_Deposit){
            val isTermAgree = mBinding.boxDefault.isChecked
            mBinding.btnPay.isEnabled = isTermAgree
        }else{
            mBinding.btnPay.isEnabled = true
        }
    }

    /**
     * 设置优惠券UI - 订单支付
     *
     * @param info 优惠券信息
     */
    private fun setCouponLayout(info: CouponRes?) {
        val couponStr = String.format(getString(R.string.Public_form_content), getString(R.string.pay_coupon), "")
        mBinding.txCoupon.text = couponStr
        if (null != info) {
            couponSelectId = info.id
            mViewModel.getPaymentPrice(BisType.Bis_Rent, orderNo, couponSelectId) //后台计算金额
            mBinding.txCouponDis.text = if (null!=info.deduction) DataHelperEx.couponDeductTx(this,symbolTx,info.deduction) else "--"
        } else {
            mBinding.txCouponDis.text = getString(R.string.payment_noCoupon)
            payAmount = amount
            isPaymentFree = false
        }
    }

    /**
     * 设置支付列表
     *
     * @param result
     */
    private fun setMethodList(result: PaymentMethodResult) {
        val payList = mutableListOf<MethodBean>()
        if (result.card)
            payList.add(
                MethodBean(DataCode.Type_NewCard, icon = R.mipmap.ic_pay_add,
                    content = getString(R.string.pay_newCardPay), des = "Visa / Madter /JCB / Union Pay /Amex", isCheck = false)
            )

        if (result.card)
            result.cardList?.let { list ->
                list.forEach { cardBean ->
                    payList.add(
                        MethodBean(DataCode.Type_Card, icon = CardIcUtil.getStripeBrandIcon(cardBean.bankName),
                            content = StrUtil.showCardNormal(cardBean.bankNo), card = cardBean, isCheck = false)
                    )
                }
                bindCardSize = list.size
            }

        if (result.google)
            payList.add(
                MethodBean(DataCode.Type_Google, icon = R.mipmap.icon_pay_google, content = getString(R.string.wallet_type_googlepay), isEnable = isGoogleReady, isCheck = false)
            )

        selectedMethodIndex = payMethodAdapter?.update(payList)?:0
    }

    /**
     * 设置顶部订单布局
     * --填充订单信息
     */
    private fun setOrderSheetLayout() {
        mBinding.txChargingFree.text = String.format(getString(R.string.Public_form_tx), getString(R.string.charge_card))
        mBinding.txCouponFree.text = String.format(getString(R.string.Public_form_tx), getString(R.string.pay_coupon))
        mBinding.txPromoFree.text = String.format(getString(R.string.Public_form_tx), getString(R.string.pay_promoCode))
        mBinding.txPlatDis.text = String.format(getString(R.string.Public_form_tx), getString(R.string.order_discount))

        mBinding.txOrderId.text = String.format(getString(R.string.Public_form_tx), getString(R.string.order_orderID))
        mBinding.txRentalDate.text = String.format(getString(R.string.Public_form_tx), getString(R.string.order_rentalDate))
        mBinding.txReturnDate.text = String.format(getString(R.string.Public_form_tx), getString(R.string.order_returnDate))
        mBinding.txRentalDuration.text = String.format(getString(R.string.Public_form_tx), getString(R.string.order_duration))
        mBinding.txRentalFees.text = String.format(getString(R.string.Public_form_tx), getString(R.string.order_orderAmount))

        orderInfo?.let { order ->
            //金额信息
            //充电卡优惠
            mBinding.clChargingFree.visibility = if (order.chargeCardDuration > 0) View.VISIBLE else View.GONE
            mBinding.tvCardValue.text = getString(R.string.coupon_freeUsage) +" "+ DataHelperEx.chargingFreeTx(this,order.chargeCardDuration)
            //优惠券折扣 : 时长免费 金额优惠 折扣租金
            mBinding.clCouponFree.visibility = if (order.userCouponId > 0) View.VISIBLE else View.GONE
            val couponDeductTx :String = if (null==order.userCouponInfo) "$symbolTx ${MathUtil.round(order.couponAmountValue())}" else {
                if (null!=order.userCouponInfo.deduction)
                    DataHelperEx.couponDeductTime(this, symbolTx, order.userCouponInfo.deduction,order.couponAmountValue())
                else
                    "--"
            }
            mBinding.tvCouponValue.text = couponDeductTx
            //优惠码折扣
            mBinding.clPromoFree.visibility = if (order.userPromoCodeId > 0) View.VISIBLE else View.GONE
            val promoDeductTx :String = if (null==order.userPromoCodeInfo) "$symbolTx ${MathUtil.round(order.promoAmountValue())}" else {
                if (null!=order.userPromoCodeInfo.deduction)
                    DataHelperEx.couponDeductTime(this, symbolTx, order.userPromoCodeInfo.deduction,order.promoAmountValue())
                else
                    "--"
            }
            mBinding.tvPromoValue.text = promoDeductTx
            //平台折扣金额:平台设置优惠金额/免单
            mBinding.clPlatformDis.visibility = if (order.platAmountValue() > 0) View.VISIBLE else View.GONE
            mBinding.tvPlatAmount.text = "$symbolTx ${MathUtil.round(order.platAmountValue())}"
            if(order.couponAmountValue()==0.0 && order.promoAmountValue()==0.0 && order.platAmountValue()==0.0){
                mBinding.lineCouponDis.visibility = View.GONE
            }else{
                mBinding.lineCouponDis.visibility = View.VISIBLE
            }
            /*订单信息*/
            mBinding.tvOrderId.text = order.orderNo.parseTx()
            mBinding.tvRentalDate.text = DateUtil.getOrderTime(order.createTime)
            if (payBisType == BisType.Bis_Loss){
                mBinding.clReturnDate.visibility = View.GONE
            }else{
                mBinding.tvReturnDate.text = DateUtil.getOrderTime(order.endTime)
            }
            //订单使用时长
            val timeArray = DateUtil.time2ArrayTime(order.getOrderDuration() * 1000)
            val dayStr = DateUtil.time0format(timeArray[0])
            val hrStr = DateUtil.time0format(timeArray[1])
            val minStr = DateUtil.time0format(timeArray[2])
            val secStr = DateUtil.time0format(timeArray[3])
            if (timeArray[0] > 0) {
                //超过天
                if (timeArray[0] > 1) {
                    mBinding.tvRentalDuration.text = String.format(getString(R.string.Order_duration_days), secStr, minStr, hrStr, dayStr)
                } else {
                    mBinding.tvRentalDuration.text = String.format(getString(R.string.Order_duration_day), secStr, minStr, hrStr, dayStr)
                }
            } else {
                mBinding.tvRentalDuration.text = String.format(getString(R.string.Order_duration_text), secStr, minStr, hrStr)
            }
            //订单租金
            mBinding.tvRentalFees.text = symbolTx+" "+MathUtil.round(order.orderAmountValue())
            //税金+支付金额
            if (order.tax>0){
                tax = order.tax
                taxAmount = order.taxAmount
                mBinding.clTaxAmount.visibility = View.VISIBLE
                val taxRotTx= getString(R.string.pay_tax) + " "+MathUtil.round(order.tax) + "%"
                mBinding.txTaxAmount.text = String.format(getString(R.string.Public_form_tx), taxRotTx)
                mBinding.tvTaxAmount.text = symbolTx + MathUtil.round(order.taxAmount)

                val payWithTx = getString(R.string.order_paymentAmount) + " ("+getString(R.string.pay_includingTax)+")"
                mBinding.txToPay.text = String.format(getString(R.string.Public_form_tx), payWithTx)
                mBinding.tvToPayAmount.text = symbolTx + MathUtil.round(order.unpaidAmountValue())
            }else{
                mBinding.clTaxAmount.visibility = View.GONE
                mBinding.txToPay.text = String.format(getString(R.string.Public_form_tx), getString(R.string.order_paymentAmount))
                mBinding.tvToPayAmount.text = symbolTx + MathUtil.round(order.unpaidAmountValue())
            }
            /*计费规则*/
            order.billing?.let { plan ->
                mBinding.tvPlanContent.text = DataHelperEx.pricePlanTx(this@PaymentCodeActivity, plan)
            }
        }
    }

    /**
     * 支付提示
     * --订单信息
     */
    private fun showOrderSheet() {
        isShowOrder = true
        mBinding.blurSpring.visibility = View.VISIBLE
        mBinding.viewOrders.visibility = View.VISIBLE
    }

    /**
     * 支付交互
     * --选择优惠券
     */
    private fun showCouponSheet() {
        couponSheetDialog?.dismiss()
        couponSheetDialog = WalletDialogUtil.instance.showCouponSelectSheet(this, couponList, selectCouponIndex,
            selectAction = {
                selectCouponIndex = it
                setCouponLayout(couponList[it])
            })
    }
    /**
     * 免费弹框
     * --当支付金额小于0.5元,支付按免费处理
     * --支付方式:钱包(-1)
     */
    private fun showFreePaymentNotify(){
        WalletDialogUtil.instance.showNotifyDialog(this,
            title = "", msg = getString(R.string.pay_freeTips),
            leftAction = {

            },
            left = getString(R.string.public_cancel),
            rightAction = {
                cardNum = ""
                mViewModel.payment(PaymentReq(
                    payType = -1,
                    type = payBisType,
                    orderNo = orderNo,
                    couponId = couponId,
                    userCouponId = (if (couponSelectId==-1) null else couponSelectId)))
            },
            right = getString(R.string.public_confirm),
            isShowLeft = true,isShowRight = true)
    }

    /**
     * 支付交互
     * --使用新卡支付
     */
    private fun showSheetCardPay() {
        if (cardPayDialog?.isVisible == true) {
            cardPayDialog?.dismiss()
            cardPayDialog = null
        }
        cardPayDialog = SheetPaymentDialog(payBisType, true, object : ICardPayListener {
            override fun onScanBankcard() {
                stripeScanSheet?.present()
            }

            override fun onPaymentByCard(param: CardParams, payParams: PaymentMethodCreateParams?, bind: Boolean, default: Boolean) {
                cardNum = param.last4
                cardPayParams = payParams
                payByCard(param, bind, default) //正式逻辑
            }
        })
        cardPayDialog?.show(supportFragmentManager, "SheetPaymentDialog")
    }

    /**
     * 支付选择--使用Google pay
     *
     * @param paymentMethodId Google Pay 回调id
     */
    private fun payByGoogle(paymentMethodId :String) {
        cardNum = ""
        mViewModel.payment(
            PaymentReq(
                payType = payMethod,
                type = payBisType,
                orderNo = orderNo,
                couponId = couponId,
                paymentTokenObject = paymentMethodId,
                userCouponId = (if (couponSelectId == -1) null else couponSelectId)
            )
        )
    }

    /**
     * 支付选择
     * --已绑定卡支付
     * @param method 支付方式对象
     */
    private fun payByBindCard(method: MethodBean) {
        method.card?.let {
            val req = PaymentReq(
                payType = payMethod,
                type = payBisType,
                orderNo = orderNo,
                couponId = couponId,
                bankcardId = it.id,
                customerId = it.customerId,
                userCouponId = (if (couponSelectId == -1) null else couponSelectId)
            )
            cardNum = it.bankNo
            mViewModel.payment(req)
        }
    }

    /**
     * 支付选择
     * --新卡卡支付
     *
     * @param param 卡参数
     * @param bind 是否需要绑定
     */
    private fun payByCard(param: CardParams, bind: Boolean, default: Boolean) {
        if (isRequestCard)
            return
        showLoadingDialog("")
        isRequestCard = true
        stripe?.createCardToken(param, callback = object : ApiResultCallback<Token> {
            override fun onError(e: Exception) {
                dismissDialog()
                errorPaymentResult(e.message?:"").run {
                    toResultActivity(false, this)
                }
                isRequestCard = false
            }

            override fun onSuccess(result: Token) {
                isRequestCard = false
                result.card?.let { ca ->
                    payMethod = DataCode.Type_NewCard
                    val cardReq = CardBindReq(
                        token = result.id,
                        bankNo = ca.last4 ?: "",
                        bankExpire = StrUtil.setCardBindExp(ca.expYear,ca.expMonth),
                        bankName = ca.brand.displayName,
                        bankType = ca.funding?.name,
                        postalCode = ca.addressZip,
                        defaulted = default,
                        save = (bind || default)
                    )
                    val req = PaymentReq(
                        payType = payMethod,
                        type = payBisType,
                        orderNo = orderNo,
                        couponId = couponId,
                        bankcardInfo = cardReq,
                        cardToken = result.id,
                        userCouponId = (if (couponSelectId == -1) null else couponSelectId)
                    )
                    mViewModel.payment(req, false)
                }
            }
        })
    }

    /**
     * 支付 前端支付
     *
     * @param clientSecret 支付秘钥
     */
    private fun requestAppPayment(clientSecret: String, params: PaymentMethodCreateParams? = null, showLoading: () -> Unit) {
        showLoading()
        val confirmParams = params?.let {
            ConfirmPaymentIntentParams.createWithPaymentMethodCreateParams(it, clientSecret)
        } ?: ConfirmPaymentIntentParams.create(clientSecret)

        stripe?.confirmPayment(this, confirmParams)
    }

    /**
     * 支付 Google 前端支付
     *
     * @param money 支付金额
     */
    private fun requestGooglePayment(money:Double){
        googleMethodLauncher?.startGooglePayment(currencyTx,amount = MathUtil.mul(money,100.0).toInt()) {
            //Loading action
            LogUtil.d("---Start Google Pay :$money")
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //Stripe 处理前端支付或者前端检验结果
        stripe?.onPaymentResult(requestCode, data, object : ApiResultCallback<PaymentIntentResult> {
            override fun onError(e: Exception) {
                dismissDialog()
                val errorStripeTx = e.message?:""
                if (null!= paymentResult){
                    paymentResult?.failedReason = errorStripeTx
                    toResultActivity(false,paymentResult!!)
                }else{
                    errorPaymentResult(errorStripeTx).run {
                        toResultActivity(false, this)
                    }
                }
            }

            override fun onSuccess(result: PaymentIntentResult) {
                dismissDialog()
                val paymentIntent = result.intent
                val status = paymentIntent.status
                LogUtil.d("---Stripe status: $status")
                if (status == StripeIntent.Status.Succeeded) {
                    paymentResult?.let {
                        if (it.type == 0)
                            it.type = payBisType
                        toResultActivity(true, it)   //跳转支付结果
                    }
                } else if (status == StripeIntent.Status.RequiresPaymentMethod) {
                    paymentResult?.let {
                        if (it.type == 0)
                            it.type = payBisType
                        it.failedReason = paymentIntent.lastPaymentError?.message.orEmpty()
                        toResultActivity(false, it)
                    }
                }
            }
        })
    }

    /**
     * 跳转失败结果
     * @param errorTx sdk错误信息
     */
    fun errorPaymentResult(errorTx:String):PaymentResult{
        return PaymentResult(paymentMethod = payMethod, type = payBisType,
            amount = payAmount, tax = tax,taxAmount = taxAmount, paymentTime = System.currentTimeMillis(), orderNo = orderNo,
            failedReason = errorTx, success = 2)
    }

    fun toResultActivity(isSuccess: Boolean, result: PaymentResult) {
        if (cardPayDialog?.isVisible == true)
            cardPayDialog?.dismiss()
        if (StrUtil.isEmpty(result.bankNo) && !StrUtil.isEmpty(cardNum)) {
            result.bankNo = cardNum
        }
        if (result.tax == 0.0){
            result.tax = tax
            result.taxAmount = taxAmount
        }
        if (isPaymentFree || result.amount==0.0)
            result.isFree = true
        if((payBisType == BisType.Bis_Rent || payBisType == BisType.Bis_Loss)
            && null!=orderInfo){
            result.orderJson = orderInfo!!.toJson()
        }
        startActivity<PaymentResultActivity>(Extra.IT_RESULT to isSuccess, Extra.IT_TYPE to result.type, Extra.IT_DATA to result.toJson())
    }

    override fun onDestroy() {
        if (null != cardPayDialog && cardPayDialog?.isVisible == true) {
            cardPayDialog?.dismiss()
        }
        super.onDestroy()
    }
}